var app = getApp();
var answerTimer = null;
function checkVal(that,num,rightAnswer){
	if(num!=rightAnswer){
		that.audioCtx.pause()
		app.tzfail(that,1,num);//挑战失败
        return false;
	}
	else{
		if (num == parseInt(that.data.maxNum)) {//当最大值500输入正确时，运行成功的提示
			that.audioCtx.pause()
			app.checkReward(that,1,num);//中奖了
        }
	}
}
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mid;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=1';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 1) {
		                        that.setData({ challeng_num: parseInt(res.data.num)});
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    }
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
    data: {
    	openid:'',
    	failtxt:'',
    	suctxt:'',
    	resetTime:0,
    	min_time:0,
    	mid:0,
    	rid:0,
    	maxNum:0,
        toTem:'Tem',
        change_time:false,
        music:'',
        err_music:'',
        sec_game:0,
        audioCtx:'',
        errAudio:'',
        g_time:'',
        gametoken:'',
        min_time:0,
        max_time:0,
        
        rightNumber:1,//动态改变正确答案
        beginCountDown: 3,//游戏开始--倒计时
        gamingOverTime: 0,//游戏开始后--fail倒计时
        gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
    },
    onHide:function(){
    	wx.pauseBackgroundAudio();
    },
    onLoad:function(options){
    	var that = this;
    	wx.showLoading({title:'数据加载中...'});
    	app.sysInit(this,function(res){
	    	app.getUserInfo(function (res) {
	        	var openid = res['openid'];
	        	//获取分享内容
	            app.getShareData(function(res){
	            	that.setData({shareData:res.data});
	            },openid,1);
	        	that.setData({openid:openid});
	        	app.util.request({
			        url: 'entry/wxapp/play',
			        data: {
			          m: 'junsion_challeng',
			          t: 1,
			          openid:openid,
			          game:1,
			        },
			        success: function (res) {
			          wx.hideLoading();
			          if(res.data.code==0 || res.data.code==2){
			        	  var code = res.data.code;
			        	  wx.showModal({
			                  title:res.data.msg,
			                  showCancel:false,
			                  success: function(res) {
			                	  wx.showLoading({title:'数据加载中...'});
			                	  if(code==2)
			                		  var url = '../index/index?gobuy=1';
			                	  else var url = '../index/index';
			                	  wx.redirectTo({
			    	    			  url: url
			    	    		  })
			                  }
		                  });
			          }
			          else{
			        	  that.setData({
			        		  gamingOverTime:res.data.sec_game,
			        		  gametoken:res.data.gametoken,
			        		  maxNum:res.data.maxNum,
			        		  mid:res.data.mid,
			        		  suctxt:res.data.suctxt,
			        		  failtxt:res.data.failtxt,
			        		  resetTime:res.data.resetTim,
			        		  min_time:res.data.min_time,
			        		  g_time:res.data.g_time,
			        		  min_time:res.data.min_time,
  							  max_time:res.data.max_time
			        	  });
			        	  that.beginCountDown();//游戏主入口
			          }
			        },
			    });
	    	});
        });
        var music = wx.getStorageSync('music');
        that.setData({
        	music:music.music,
        	err_music:music.err_music,
  	    });
        
    },
    onReady: function () {   
        this.audioCtx = wx.createAudioContext('myAudio')
        this.errAudio = wx.createAudioContext('errAudio')
        this.audioCtx.play()
    },
    onShow:function(){

    },
    // 游戏开始倒计时
    beginCountDown: function () {
        var that = this;
        var countTime = this.data.beginCountDown;
        var timer = setInterval(function () {
            that.setData({beginCountDown: --countTime});
            if (countTime <= 0) {
                clearInterval(timer);
                that.gamingInit(that.data.maxNum, that.data.gamingOverTime);//调用--游戏初始化
            }
        }, 1000)
    },
    /***游戏初始化。
        参数说明，
        maxNum：游戏数字长度，
        minTime最小刷新键盘顺序s,
        maxTime最大刷新键盘顺序s,
        gamingOverTime游戏开始时--game over倒计时
    ***/
    gamingInit: function (maxNum, gamingOverTime) {
        this.creatGamingLength(maxNum);//创建数字数组
        this.gamingOver(gamingOverTime);//动态刷新over倒计时
        this.resetTime();//动态刷新数字顺序
    },
    //游戏running-点击数字
    play:function(e){
        var that=this;
        var idx = e.currentTarget.dataset.idx;
        var nb = e.currentTarget.dataset.nb;
        if (that.data.gamingStatus === 'running'){
        	checkVal(that,nb,that.data.rightNumber);
        	if (nb === that.data.rightNumber) {
                that.data.gamingArr[idx].status = 'active';
                that.setData({
                    rightNumber: ++that.data.rightNumber,
                    gamingArr: that.data.gamingArr
                })
                if (that.data.gamingArr.every(item => item.status ==='active')){//游戏挑战成功
                    that.setData({
                        gamingStatus:'success'
                    })
                }
            } else {
                that.data.gamingArr[idx].status = 'fail';
                that.setData({
                    gamingArr: that.data.gamingArr,
                    gamingStatus: 'fail'
                })
            }
        }      
    },
    //生成游戏数组，如：1-49，参数val游戏长度
    creatGamingLength: function (val) {
        var gamingArr = [], emptyArr = [];
        for (let a = 0; a < val; a++) {
            let arr = { number: a + 1, status: 'default', bgImgId: Math.ceil(Math.random() * 5) };
            gamingArr.push(arr);
        }
        if (val % 7 !== 0) {//emptyArr用于拉满最后一行，解决css-flex尾行bug
            for (let b = 0; b < 7 - val % 7; b++) {emptyArr.push(b);}
        }
        this.setData({
            gamingArr: gamingArr,
            emptyArr: emptyArr,
            gamingStatus: 'running'
        })
    },
    //游戏开始时--game over倒计时
    gamingOver:function(time){
        var that = this;
        var timer = setInterval(function () {
            time--;
            if (time <= 1) {
                clearInterval(timer);
                that.setData({gamingStatus:'fail'})
                that.audioCtx.pause()
                that.errAudio.play()
		        //挑战失败3秒后回到首页
		        setTimeout(function(){
		        	that.errAudio.pause()
		            wx.showLoading();
		        	wx.redirectTo({
			  	    	url: '../tzfail/tzfail'
			  	    })
		        },1500);
            } else if (that.data.gamingStatus === 'success' || that.data.gamingStatus === 'fail'){
                clearInterval(timer);
            }
            that.setData({gamingOverTime: time});
        }, 1000)
    },
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  //随机时长--调整数字顺序---minTime最小刷新键盘顺序s,maxTime最大刷新键盘顺序s。
  resetTime: function () {
      var that = this;
      if(that.data.change_time) return false;
      if(parseInt(that.data.min_time)<=0){
		    that.setData({change_time : true});
	    }
      that.setData({
		  gamingStatus: 'running'
      })
  	var resetTime = app.fRandomBy(parseInt(that.data.min_time),parseInt(that.data.max_time))
  	that.resetGamingArr();
      answerTimer=setInterval(function(){
          resetTime--;
          if(resetTime>=1){
        	  that.setData({
                  resetTime: resetTime
              })
          }
          if (resetTime < 0) {
        	  that.setData({
        		  gamingStatus: 'notBegin'
              })
              clearInterval(answerTimer);
              that.resetTime();
          }
      },1000);
  },
    //调整数字顺序
    resetGamingArr: function () {
        var gamingArr = this.data.gamingArr;
        var temGamingArr = [];
        for (var i = 0, len = gamingArr.length; i < len; i++) {
            var j = Math.floor(Math.random() * gamingArr.length);
            temGamingArr[i] = gamingArr[j];
            gamingArr.splice(j, 1);
        };
        this.setData({gamingArr: temGamingArr});
    }
})